#/usr/bin/python
# coding: utf8

import time
import win32api
import win32con
from  PAM30 import PAM30
import urllib
from datetime import datetime

'''
先设置ie为代理有效
根据代理ip列表，逐个测试ip是否有效
然后修改代理的ip，访问ip168查看是否改变ip
'''


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    root = win32con.HKEY_CURRENT_USER
    key = win32api.RegOpenKey(root, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv):
            return True
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def proxy(enable):
    keystr = 'Software\Microsoft\Windows\CurrentVersion\Internet Settings'
    if enable:
        setRegValue(keystr, 'ProxyEnable', 1)
    else:
        setRegValue(keystr, 'ProxyEnable', 0)


def checkproxy(ip):
    '''
    测试代理ip是否有效
    '''
    try:
        proxies = {'http': 'http://'+ip}
        testurl = "http://www.taogezi.org/Public/images/tgz.jpg"
        filehandle = urllib.urlopen(testurl, proxies=proxies)
        html=filehandle.read()
        if len(html)==74619:
            return True
        else:
            return False
    except:
        return False


def testporxy(ips):
    '''
    根据ip列表测速
    '''
    a={}
    for ip in ips:
        start=datetime.now()
        flag = checkproxy(ip)
        end=datetime.now()
        if flag:
            print ip, 'used', end-start, 'time'
            a[end-start]=ip
            b=sorted(a)
            print 'Fast list :'
            i = 0
            for ix in a:
                print 'No.', i, ': ', a[b[i]]
                ie.navigate("http://www.ip168.com/")
                time.sleep(5)
                i = i + 1


if __name__ == '__main__':
    ie = PAM30.PAMIE()
    ie.navigate('http://www.ip168.com/')
    proxylist = ['122.113.28.52:3128', '124.205.178.62:80', '118.85.207.23:80']
    proxylist.append('61.160.253.136:80')
    proxy(True)
    testporxy(proxylist)
    time.sleep(2)
